<template>
  <div>
    <div class="crumbs">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item><i class="el-icon-menu"></i> 首页</el-breadcrumb-item>
        <el-breadcrumb-item>附件管理</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <div class="handle-box">
      <!--<el-form ref="serch" :model="serch" :inline="true">
        <el-form-item label="模块">
          <el-select v-model="serch.protype" size="small" placeholder="所属模块" class="handle-select mr10">
            <el-option :key="1" label="文章" :value="1"></el-option>
            <el-option :key="2" label="产品" :value="2"></el-option>
            <el-option :key="3" label="用户" :value="3"></el-option>
            <el-option :key="4" label="关于我们" :value="4"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="small" @click="doSearch" plain round>搜索</el-button>
          <el-button type="danger" icon="el-icon-delete" size="small" @click="doClean"  plain round>清空</el-button>
          <el-button type="success" class="handle-del mr10" size="small" round icon="el-icon-plus" @click="addOrEdit('add',null)" plain>添加附件</el-button>
        </el-form-item>
      </el-form>-->
      <el-button type="danger" class="handle-del mr10" size="small" round icon="el-icon-back"
                 @click="routerBack" plain>返回
      </el-button>
      <el-button type="success" class="handle-del mr10" size="small" round icon="el-icon-upload"
                 @click="addOrEdit('add',null)" plain>添加附件
      </el-button>
      <span style="margin-left: 20px;color: red;font-size: 10px;">*点击图片可预览</span>
    </div>
    <el-table :data="page.list" stripe :height=500 style="width: 100%">
      <el-table-column header-align="center" label="文件" sortable>
        <template slot-scope="scope">
          <img :src="scope.row.filepath" style="height: 80px;" @click="imagePreview(scope.row.filepath)"/>
        </template>
      </el-table-column>
      <el-table-column prop="filename" header-align="center" label="附件名称" sortable>
      </el-table-column>
      <el-table-column prop="business" header-align="center" label="原文件名" sortable>
      </el-table-column>
      <el-table-column prop="type" header-align="center" label="文件类型" sortable>
      </el-table-column>
      <!--<el-table-column prop="filepath" header-align="center" label="路径">
      </el-table-column>-->
      <el-table-column header-align="center" label="所属模块">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.modularflag===1">文章</el-tag>
          <el-tag v-else-if="scope.row.modularflag===2">产品</el-tag>
          <el-tag v-else-if="scope.row.modularflag===3">用户</el-tag>
          <el-tag v-else-if="scope.row.modularflag===4">关于我们</el-tag>
          <el-tag v-else>其他</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" header-align="center" width="180">
        <template scope="scope">
          <!--<el-button size="small" type="primary" icon="el-icon-edit"
                     @click="addOrEdit('update', scope.row)" round plain>编辑
          </el-button>-->
          <el-button size="small" type="danger" icon="el-icon-delete"
                     @click="handleDelete(scope.$index, scope.row)" round plain>删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page.sync="page.currentPage"
        :page-size="page.pageSize"
        layout='prev, pager, next, jumper, ->, total'
        :total="page.total">
      </el-pagination>
    </div>


    <el-dialog
      title="编辑产品信息 （点击图片可预览）"
      :visible.sync="attachmentDialogVisible"
      width="50%"
      :close-on-click-modal="false"
      max-height="400px"
      top="25px"
      :before-close="dailogCloseAttachemnt" center>
      <el-table
        ref="multipleTable"
        tooltip-effect="dark"
        @selection-change="handleSelectionChange"
        :data="pageAttachment.list"
        stripe
        :height=500
        style="width: 100%">
        <el-table-column
          type="selection"
          width="55">
        </el-table-column>
        <el-table-column prop="filename" header-align="center" label="预览" sortable>
          <template slot-scope="scope">
            <img :src="scope.row.filepath" style="height: 60px;" @click="imagePreview(scope.row.filepath)"/>
          </template>
        </el-table-column>
        <el-table-column prop="filename" header-align="center" label="附件名称" sortable>
        </el-table-column>
        <el-table-column prop="business" header-align="center" label="原附件名称">
        </el-table-column>
        <el-table-column header-align="center" label="附件类型">
          <template slot-scope="scope">
            <el-tag>{{scope.row.type}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="filesize" header-align="center" label="附件大小">
        </el-table-column>
      </el-table>
      <!--<div class="pagination">
        <el-pagination
          @size-change="handleSizeChangeAttachment"
          @current-change="handleCurrentChangeAttachment"
          :current-page.sync="page.currentPage"
          :page-size="pageAttachment.pageSize"
          layout='prev, pager, next, jumper, ->, total'
          :total="pageAttachment.total">
        </el-pagination>
      </div>-->
      <el-button @click="dailogCloseAttachemnt">取 消</el-button>
      <el-button type="primary" @click="save" :disabled="saveBtnDisabled">确 定</el-button>
    </el-dialog>

    <el-dialog
      title="图片预览"
      :visible.sync="imagedialogVisible"
      :fullscreen="true">
      <img :src="imagePath"/>
    </el-dialog>
  </div>
</template>

<script>
  import common from '../../../common/constant.js'
  import {handleStrLength} from '../../../common/filter'
  import ElFormItem from "../../../../node_modules/element-ui/packages/form/src/form-item";
  import ElCol from "element-ui/packages/col/src/col";
  import ElTag from "../../../../node_modules/element-ui/packages/tag/src/tag";
  export default {
    components: {
      ElTag,
      ElCol,
      ElFormItem
    },
    data() {
      const current = 1
      return {
        imagePath: '',
        imagedialogVisible: false,
        saveBtnDisabled: true,
        selectedRow: [],
        multipleTable: [],
        attachmentDialogVisible: false,
        recordId: 0,
        modularFlag: 0,
        centerDialogVisible: false,
        url: '../../../static/vuetable.json',
        tableData: [],
        cur_page: 1,
        multipleSelection: [],
        select_cate: '',
        select_word: '',
        products: [],
        page: {
          pageSize: 20,
          currentPage: current,
          totle: 0,
          list: []
        },
        pageAttachment: {
          pageSize: 10,
          currentPage: current,
          totle: 0,
          list: []
        },
        currentPageNum: current,
        serch: {
          modularFlag: 2
        },
        attachmentRelation: {
          id: 0,
          modularflag: 0,//功能标志
          recordid: 0,//管理功能记录ID
          attachmentid: 0,//附件ID
          filename: '',
          filepath: '',
          filesize: '',
          business: '',
          type: ''
        },
        rules: {
          productname: [
            {required: true, message: '请填写产品名称', trigger: 'blur'},
            {min: 1, max: 15, message: '长度在 1 到 15 个字符', trigger: 'blur'}
          ],
          productxlname: [
            {required: true, message: '请填写产品别名', trigger: 'blur'},
            {min: 1, max: 15, message: '长度在 1 到 15 个字符', trigger: 'blur'}
          ],
          protype: [
            {required: true, type: 'number', message: '请选择产品分类', trigger: 'blur'},
          ],
          odr: [
            {type: 'number', message: '排序值必须为数字值', trigger: 'change'}
          ],
          hotNum: [
            {type: 'number', message: '排序值必须为数字值', trigger: 'change'}
          ],
          scnum: [
            {required: true, message: '请填写生产许可证编号', trigger: 'blur'},
            {min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur'}
          ]
        }
      }
    },
    created(){
      this.recordId = this.$route.query.recordId
      this.modularFlag = this.$route.query.modularFlag
      this.query();
    },
    methods: {
      routerBack(){
        this.$router.back()
      },
      handleSizeChange(value){
        console.log(`每页 ${val} 条`);
      },
      handleCurrentChange(val) {
        let self = this
        self.currentPageNum = val
        this.query()
      },
      handleSizeChangeAttachment(value){
        console.log(`每页 ${val} 条`);
      },
      handleCurrentChangeAttachment(val) {
        let self = this
        self.currentPageNum = val
        this.query()
      },
      doSearch(){
        this.modularFlag = this.serch.modularFlag
        this.query()
      },
      doClean(){
        this.serch = {
          modularFlag: 2
        }
        this.query()
      },
      imagePreview(path){
        this.imagePath = path
        this.imagedialogVisible = true
      },
      dailogClose(){
        this.centerDialogVisible = false
        this.$refs['product'].resetFields()
        this.attachmentRelation = {
          id: 0,
          modularflag: 0,//功能标志
          recordid: 0,//管理功能记录ID
          attachmentid: 0,//附件ID
          filename: '',
          filepath: '',
          filesize: '',
          business: '',
          type: ''
        }
      },
      dailogCloseAttachemnt(){
        this.pageAttachment = {
          pageSize: 10,
          currentPage: this.current,
          totle: 0,
          list: []
        }
        this.attachmentDialogVisible = false
      },
      handleSelectionChange(selection) {
        let self = this
        self.selectedRow = selection
        if (selection !== undefined && selection.length > 0) {
          self.saveBtnDisabled = false
        } else {
          self.saveBtnDisabled = true
        }
      },
      addOrEdit(action, row){
        let self = this
        self.$http.post('/api/attachment/other', {
          'recordId': self.recordId,
          'pageSize': self.pageAttachment.pageSize,
          'pageNum': self.pageAttachment.currentPage
        })
          .then((response) => {
            let responseData = response.data
            if (responseData.flag === common.respons.seccuss) {
              self.myFileList = []
              self.pageAttachment = responseData.pageData
              self.attachmentDialogVisible = true
            } else {
              this.$notify.error({
                title: '错误',
                message: '查询失败！',
                duration: 6000
              })
            }
          })
          .catch(function (response) {
            this.message_error()
          })
      },
      save(){
        let self = this
        let selected = self.selectedRow
        let attachmentIds = []
        for (let item of selected) {
          attachmentIds.push(item.id)
        }
        self.$http.post('/api/attachmentRelation/save', {
          'recordid': self.recordId,
          'modularflag': self.modularFlag,
          'attachmentIds': attachmentIds
        })
          .then((response) => {
            let responseData = response.data
            if (responseData.flag === common.respons.seccuss) {
              self.attachmentDialogVisible = false
              self.query()
            } else {
              self.message_error()
            }
          })
          .catch(function (response) {
            self.message_error()
          })
      },
      query(){
        let self = this
        self.$http.post('/api/attachmentRelation', {
          'id': self.attachmentRelation.id,
          'deleted': common.recordStatus.normal,
          'modularflag': self.modularFlag,
          'recordid': self.recordId,
          'attachmentid': self.attachmentRelation.attachmentid,
          'pageSize': self.page.pageSize,
          'pageNum': self.currentPageNum,
        })
          .then((response) => {
            let responseData = response.data
            if (responseData.flag === common.respons.seccuss) {
              self.page = responseData.pageData
            } else {
              self.message_error()
            }
          })
          .catch(function (response) {
            self.message_error()
          })
      },

      filterTag(value, row) {
        return row.tag === value;
      },
      handleEdit(index, row) {
        this.$message('编辑第' + (index + 1) + '行');
      },
      handleDelete(index, row) {
        let self = this
        self.$alert('注意，删除后不能恢复，确认删除？', '标题名称', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          callback: action => {
            self.$http.get('/api/attachmentRelation/delete/' + row.id)
              .then((response) => {
                let responseData = response.data
                if (responseData.flag === common.respons.seccuss) {
                  self.message_ok('删除产品成功！')
                  self.query()
                } else {
                  self.message_error()
                }
              })
              .catch(function (response) {
                self.message_error()
              })
          }
        });
      },
      strLength(value){
        if (!value) {
          return ''
        }
        let remark = value.remark
        if (remark === undefined || remark === '') {
          return ''
        }
        return remark.substr(0, 15) + '....'
      },
      message_error(message) {
        this.$notify.error({
          title: '错误',
          message: message === undefined ? '操作失败' : message
        });
      },
      message_ok(message) {
        this.$notify({
          title: '成功',
          message: message === undefined ? '操作成功' : message,
          type: 'success'
        });
      }
    }
  }
</script>

<style scoped>

</style>
